﻿///////////////////////////////////////////////////
/// toto Code
/// $Id: thread.h 2 2009-12-14 12:41:06Z tonyjobmails $
/// $Date: 2009-12-14 20:41:06 +0800 (一, 14 12月 2009) $
/// $Author: tonyjobmails $
/// $Revision: 2 $
/// E-mail: tonyjobmails@gmail.com
/// filename: thread.h
/// function: 线程基类的定义
///////////////////////////////////////////////////

#ifndef __CTHREAD__H
#define __CTHREAD__H

#include <string>
#include <pthread.h>
#include <unistd.h>
#include "Mutex.h"
#include "Cond.h"
#include "CType.h"

enum
{
	THREAD_STATE_CREATE = 0,		/// 线程对象创建
	THREAD_STATE_ALIVE,			/// 线程运行
	THREAD_STATE_SLEEP,			/// 线程休眠
	THREAD_STATE_END,			/// 线程结束
};

class CThread
{
	public:
		CThread(const std::string &_name, unsigned short _state = THREAD_STATE_CREATE,
				bool _joinable = true, pthread_t _thread = 0)
			: name(_name), thread(_thread), state(_state), joinable(_joinable)
		{}

		virtual ~CThread()
		{}

		/// 得到线程ID
		pthread_t getID()
		{
			return ::pthread_self();
		}

		/// 线程休眠(秒)
		static void sleep(const long sec)
		{
			::sleep(sec);
		}

		/// 线程休眠(毫秒)
		static void msleep(const long msec)
		{
			::usleep(msec * 1000);
		}

		/// 线程休眠(微秒)
		static void usleep(const unsigned long usec)
		{
			::usleep(usec);
		}

		/// 得到线程名
		std::string getName()
		{
			return this->name;
		}

		/// 线程是否是joinable的
		bool isJoinable()
		{
			return joinable;
		}

		/// 线程是否是活动状态
		bool isAlive()
		{
			return (this->state == THREAD_STATE_ALIVE);
		}

		/// 线程是否是休眠状态
		bool isSleep()
		{
			return (this->state == THREAD_STATE_SLEEP);
		}

		/// 线程是否是结束状态
		bool isEnd()
		{
			return (this->state == THREAD_STATE_END);
		}

		/// 设置线程为结束状态
		void end()
		{
			this->state = THREAD_STATE_END;
		}

		/// 线程开始
		bool start();

		/// 线程方法
		static void* threadFunc(void *arg);

		/// 线程主回调函数，派生类需要重新定义
		virtual void run() = 0;

		/// 等待线程结束
		void join();

	private:
		std::string name;			/// 线程名
		pthread_t thread;			/// 线程ID
		Tpdef::WORD state;			/// 线程状态
		bool joinable;				/// 线程是否join
		CMutex mutex;				/// 互斥锁
		CCond cond;				/// 条件变量
};

#endif	/// __CTHREAD__H
